package com.xxx.springboot.config;

import com.xxx.springboot.pojo.entity.ShiroUser;
import com.xxx.springboot.service.ShiroUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * ①Shiro认证
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    private ShiroUserService shiroUserService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("进入授权方法！");
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("进入认证方法！");
        // 将token进行转换，token是前端页面传过来的用户名+密码的加密封装
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;

//        // 用户名和密码，应该从数据库中取，这里用静态数据代替
//        String name = "admin";
//        String password = "12345";
//        // 用户名校验
//        if(!usernamePasswordToken.getUsername().equals(name)) {
//            return null;  // 返回null的话，会自动抛出UnknownAccountException异常
//        }

        // 从数据库里获取用户名、密码进行校验
        String username = usernamePasswordToken.getUsername();
        ShiroUser shiroUser = shiroUserService.getUserByName(username);
        if(shiroUser==null) {
            return null;    // 返回null的话，会自动抛出UnknownAccountException异常
        }
        String password = shiroUser.getPassword();  // 必须得有password

        // 密码校验，Shiro自动完成
        return new SimpleAuthenticationInfo("",  password, "");
    }

}
